# Contributor: Klemens Nanni <kn@openbsd.org>
# Maintainer: Klemens Nanni <kn@openbsd.org>

# when changing _ver we *must* bump _rel
_name=vmm_clock
_ver=0.2.0
_rel=0

# kernel version
# when changing _kver/_krel make sure _rel=0
_flavor=${FLAVOR:-lts}
_kpkg="linux-$_flavor"
_kver=6.6.9
_krel=0
_kpkgver="$_kver-r$_krel"

# for custom kernels set $FLAVOR
case $CARCH in
# see $arch comment
x86|x86_64) _extra_flavors="virt";;
esac

pkgname="$_name-$_flavor"
pkgver=$_kver
pkgrel=$(( _rel + _krel ))

pkgdesc="clocksource under OpenBSD VMM"
url="https://github.com/voutilad/vmm_clock"
# amd64-only https://man.openbsd.org/vmm.4 supports i386 and amd64 guests
arch="x86 x86_64"
license="GPL-2.0-only"
depends="$_kpkg=$_kpkgver"
makedepends="$_kpkg-dev=$_kpkgver"
source="$_name-$_ver.tar.gz::https://github.com/voutilad/vmm_clock/archive/refs/tags/$_ver.tar.gz"
builddir="$srcdir/$_name-$_ver"
options="!check" # no tests

for f in $_extra_flavors; do
	makedepends="$makedepends linux-$f-dev=$_kpkgver"
	subpackages="$subpackages $_name-$f:_extra"
done

prepare() {
	default_prepare
	# verify the kernel version
	local _kapkbuild="$startdir/../../main/linux-$_flavor-/APKBUILD"
	if [ -f "$_kapkbuild" ]; then
		(	. $_kapkbuild
			pkgname=$_name-$_flavor
			[ "$_kver" != "$pkgver" ] && die "please update _kver to $pkgver"
			[ "$_krel" != "$pkgrel" ] && die "please update _krel to $pkgrel"
			return 0
		)
	fi
	local flavor=
	for flavor in $_flavor $_extra_flavors; do
		cp -r "$builddir" "$srcdir/$flavor"
	done
}

build() {
	local flavor= kabi=
	for flavor in $_flavor $_extra_flavors; do
		kabi="$_kver-$_krel-$flavor"
		make -C "$srcdir/$flavor" KERNELRELEASE="$kabi"
	done
}

package() {
	local flavor= kabi= module= modules="vmm_clock"
	for flavor in $_flavor $_extra_flavors; do
		kabi="$_kver-$_krel-$flavor"
		for module in $modules; do
			install -Dm644 "$srcdir/$flavor/$module.ko" \
				"$pkgdir/lib/modules/$kabi/extra/$module.ko"
		done
		printf '%s\n' $modules |
			install -D -m644 /dev/stdin \
				"$pkgdir/lib/modules-load.d/$_name-$flavor".conf
	done
}

_extra() {
	local flavor=${subpkgname##*-}
	depends="linux-$flavor=$_kpkgver"
	pkgdesc="$pkgdesc for $flavor kernel"

	amove \
		lib/modules/*-$flavor \
		lib/modules-load.d/*-$flavor.conf
}

sha512sums="
00d6f74cb78d01ed641225e0d74e0dbc892372722712a5981c553d6a50e9014114c1c65a2f8a222be4caa82b08e7acc56805add958e89da996d28266a92da2c6  vmm_clock-0.2.0.tar.gz
"
